package com.ishell.generate.pattern.strategy;

import com.ishell.generate.ColumnDesc;
import com.ishell.generate.TableDesc;
import com.ishell.generate.util.JdbcUtil;
import com.ishell.generate.util.PropertyUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author: crazier.huang
 * @project: generate
 * @date: 2018/7/12
 * @desc: 生产mysql列
 */
public class GenColunmnMysqlStrategy implements GenColumnStrategy {
    private final static Logger logger = LoggerFactory.getLogger(GenColunmnMysqlStrategy.class);


    String columnSql = "select TABLE_NAME,COLUMN_NAME,COLUMN_COMMENT,DATA_TYPE,COLUMN_KEY from " +
            "  INFORMATION_SCHEMA.COLUMNS where TABLE_SCHEMA = ? and TABLE_NAME = ?;";


    @Override
    public List<TableDesc> genColumn(List<TableDesc> tableDescList) {
        try {
            JdbcUtil jdbcUtil = new JdbcUtil();
            jdbcUtil.getConnection();
            for (TableDesc tableDesc : tableDescList) {
                List<Map<String,Object>> clist = jdbcUtil.findResult(columnSql,PropertyUtil.getValue("db.name"),tableDesc.getName());
                List<ColumnDesc> columnDescList = new ArrayList<>();

                for (Map<String,Object> cmap:clist) {
                    ColumnDesc columnDesc = new ColumnDesc(cmap);
                    columnDescList.add(columnDesc);
                }
                tableDesc.setColumns(columnDescList);

            }
            return tableDescList;
        } catch (SQLException e) {
            logger.error("脚本执行出错{}",e);
            return null;
        }


    }
}
